// pages/expressGet/expressGet.js
import WxValidate from "../../utils/WxValidate";
import utils from "../../utils/util";
const {
  showValidateModal,
  cklogin
} = require("../../utils/showValidateModal");
const app = getApp();
Page({
  //选择快递大小
  chooseType(e) {
    const index = Number(e.target.dataset.index);
    wx.showToast({
      title: `${this.data.expressType[index].tips}`,
      icon: "none",
      duration: 1500,
      mask: false,
    });
    this.setData({
      current: e.target.dataset.index,
      Reward: this.data.expressType[index].money,
      expressNumIndex: 0,
    });
  },
  //选择快递商家
  bussinessChange(e) {
    const index = e.detail.value;
    this.setData({
      bussinessIndex: index,
      "form.bussiness": this.data.bussinessArray[index],
    });
  },
  //取件信息、备注信息 输入框防抖
  timeID: 0, //定时器ID
  handleInput(e) {
    const {
      name
    } = e.currentTarget.dataset;
    const {
      value
    } = e.detail;
    clearTimeout(this.timeID); //清楚timeID对应的定时器，即取消相应函数的执行
    this.timeID = setTimeout(() => {
      if (name === "expressInfo") {
        this.setData({
          "form.expressInfo": value
        });
      } else {
        this.setData({
          "form.mark": value
        });
      }
    }, 1000);
  },
  //显示更多隐藏信息
  handleisHidden() {
    this.setData({
      isHidden: !this.data.isHidden,
    });
  },
  //取件信息 上传图片
  uploadImg() {
    //调用wx.chooseMedia API打开图片选择窗口
    wx.chooseMedia({
      count: 1,
      mediaType: ["image"],
      sourceType: ["album", "camera"],
      sizeType: ["original", "compressed"],
      success: (res) => {
        //chooseMedia成功回调
        wx.showLoading({
          title: "上传中"
        }); //使用wx.uploadFile将图片发至服务端上传
        wx.uploadFile({
          filePath: res.tempFiles[0].tempFilePath, //文件暂存路径
          name: "img", //文件对应的 key
          url: `${app.globalData.server}/uploadImg`, //服务端路由
          success: (result) => {
            //成功回调 //result.data为字符串，使用JSON.parse转成对象
            let filePath = JSON.parse(result.data).path;
            //文件路径为\反斜杠，需要转为斜杠/，使用正则表达式进行过滤转换
            filePath = filePath.replace(/\\/g, "/");
            let form = this.data.form; //将完整的文件路径（含有域名信息）赋值给userInfo
            form.img = `${app.globalData.server}/${filePath}`;
            this.setData({
              form
            });
            wx.hideLoading({});
            wx.showToast({
              title: "上传成功",
              icon: "success"
            });
          },
          fail: (e) => {
            //失败回调 console.log(e)
            wx.hideLoading({});
            wx.showToast({
              title: "上传失败",
              icon: "error"
            });
          },
        });
      },
      fail: (error) => {
        //chooseMedia失败回调
        console.log(error);
        wx.showToast({
          title: "上传失败",
          icon: "error"
        });
      },
    });
  },
  //选择地址
  toSelectAddress() {
    wx.redirectTo({
      url: "../address/address"
    });
  },
  //免责声明
  showStatment() {
    wx.showModal({
      title: "用户条款&隐私策略",
      content: "这里是隐私条款具体内容",
      showCancel: false,
    });
  },
  //期望送达
  expectSend(e) {
    this.setData({
      arriveIndex: e.detail.value,
      "form.arriveTime": this.data.arriveTimeArray[e.detail.value],
    });
  },
  /* 性别限制 */
  ssexStrict(e) {
    const value = e.detail.value;
    this.setData({
      genderIndex: value,
      "form.genderLimit": this.data.genderArray[value],
    });
  },
  /* 路由地址跳转 */
  handleaddress() {
    wx.navigateTo({
      url: "../addres/addres",
    });
  },
  /* 赏金加赏 */
  moneryChange() {
    if (this.data.isReward) {
      this.setData({
        "form.payMoney": this.data.Reward + parseInt(this.data.isMonery),
      });
    } else {
      this.setData({
        "form.payMoney": this.data.Reward,
      });
    }
  },
  /* 快递数量 */
  num(e) {
    const value = e.detail.value;
    const accumulated = Number(value) + 1;
    this.setData({
      expressNumIndex: value,
      Reward: this.data.current !== -1 ?
        this.data.expressType[this.data.current].money * accumulated :
        "请选择快递",
      "form.expressNum": this.data.expressNumArray[value],
    });
  },
  /* 加急悬赏 */
  dotHandle() {
    this.setData({
      isReward: !this.data.isReward,
      isRewardHidden: !this.data.isRewardHidden,
    });
  },
  /**
   * 页面的初始数据
   */
  data: {
    MoneyEnd: 2,
    current: -1,
    expressType: [{
        name: "小件",
        tips: "小件：手机巴掌大小的快件，价格3元",
        money: 3
      },
      {
        name: "中件",
        tips: "中件：鞋服盒子大小的快件，价格5元",
        money: 5
      },
      {
        name: "大件",
        tips: "大件：重量超过5公斤的快件，价格8元",
        money: 8
      },
    ],
    Reward: 0, //赏金
    bussinessArray: [
      "请选择快递点",
      "圆通速递(校外)",
      "顺丰快递(正大门)",
      "百世快递 (小北门)",
      "中通快递(小北门)",
      "邮政包裹(校外)",
    ], //快递商家数组
    bussinessIndex: 0, //选中得快递商家数组下标
    isReward: false, //额外赏金开关
    isRewardHidden: true,
    isMonery: 0,
    isHidden: true, //在data中增加 显示/隐藏开关 更多信息
    arriveTimeArray: ["不限制", "尽快送达", "今天中午", "今天晚上"],
    arriveIndex: 0,
    genderArray: ["不限制性别", "只限男生", "只限女生"],
    genderIndex: 0,
    expressNumArray: ["1个", "2个", "3个"],
    expressIndex: 0,
    form: {
      expressType: "", //快递类型
      address: "", //收件地址
      bussiness: "", //快递商家
      img: "", //取件截图
      expressInfo: "", //取件信息
      mark: "", //备注信息
      arriveTime: "不限制", //期望送达
      genderLimit: "不限制性别", //性别限制
      expressNum: 1, //快递数量
      payMoney: 0, //最终付款金额，默认3元为小件的金额
    },
    priseMoney: 0, //赏金
  },
  //提交表单
  async submitForm() {
    // console.log(this.data.form.payMoney);
    //判断当前用户是否已授权登录
    const r = await cklogin(app.globalData.userInfo);
    if (!r) {
      return false;
    }
    const {
      expressType,
      address,
      bussiness,
      img,
      expressInfo,
      mark,
      arriveTime,
      genderLimit,
      expressNum,
      payMoney,
    } = this.data.form;
    //判断 地址、商家是否已获取
    const params = {
      address,
      bussiness
    };
    if (!this.WxValidate.checkForm(params)) {
      const errors = this.WxValidate.errorList[0];
      showValidateModal(errors);
      return false;
    }
    //检查 取件信息
    if (!img && !expressInfo) {
      wx.showModal({
        title: "提示",
        content: "请输入取件码或上传截图",
        showCancel: false,
      });
      return false;
    }
    //声明发布数据时间变量，值为当前时间
    const publicTime = utils.formatTime(new Date());
    //保存数据库
    wx.showLoading({});
    wx.request({
      url: `${app.globalData.server}/addOrder`,
      method: "POST",
      data: {
        orderType: "快递代取",
        openid: app.globalData.userInfo.openid,
        endAddress: address,
        //目的地
        startAddress: `快递点-${bussiness}`,
        //起点
        payMoney,
        //支付金额
        status: "待帮助",
        //订单状态
        publicTime,
        //发布时间
        info: {
          //其他信息
          expressType, //快递大小
          img, //取件图片
          expressInfo, //取件信息
          mark, //备注信息
          arriveTime, //期望送达
          genderLimit, //性别限制
          expressNum, //快递数量
        },
        userInfo: app.globalData.userInfo, //发布者的个人信息
      },
      success: (res) => {
        wx.hideLoading({});
        if (res.data == "success") {
          wx.showToast({
            title: "提交成功",
            icon: "success"
          });
          setTimeout(() => {
            wx.switchTab({
              url: "../order/order"
            });
          }, 1000);
        } else {
          wx.hideLoading({});

          wx.showToast({
            title: "发布失败",
            icon: "error"
          });
        }
      },
      fail: (err) => {
        wx.hideLoading({});
        wx.showToast({
          title: "发布失败",
          icon: "error"
        });
      },
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initValidate();
  },
  initValidate() {
    // 验证字段的规则
    const rules = {
      address: {
        required: true
      },
      bussiness: {
        required: true
      },
    };
    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      address: {
        required: "请选择收件地址"
      },
      bussiness: {
        required: "请选择快递商家"
      },
    };
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.Id1 = setInterval(() => {
      if (this.data.isReward) {
        this.setData({
          "form.payMoney": this.data.Reward + parseInt(this.data.isMonery),
        });
      } else {
        this.setData({
          "form.payMoney": this.data.Reward,
        });
      }
    }, 500);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearInterval(this.Id1);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});